import { Global, Logger, Module } from '@nestjs/common';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as dotenv from 'dotenv';
import { TypeOrmModule, type TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigEnum } from './enum/config.enum';
import { UserModule } from './user/user.module';
import { LogModule } from './log/log.module';
import { AuthModule } from './auth/auth.module';
import { ApiResponseInterceptor } from './interceptor/response.interceptor';
import { ApiExceptionFilter } from './filter/exception.filter';
import { RoleModule } from './role/role.module';
import { HeroModule } from './hero/hero.module';
import { UploadModule } from './upload/upload.module';

@Global()
@Module({
  imports: [
    // =========================================== 系统模块 ===========================================
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env.${process.env.NODE_ENV}`,
      load: [() => dotenv.config({ path: '.env' })],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) =>
        ({
          type: configService.get(ConfigEnum.DB_TYPE),
          host: configService.get(ConfigEnum.DB_HOST),
          port: configService.get(ConfigEnum.DB_PORT),
          username: configService.get(ConfigEnum.DB_USERNAME),
          password: configService.get(ConfigEnum.DB_PASSWORD),
          database: configService.get(ConfigEnum.DB_NAME),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          synchronize: configService.get(ConfigEnum.DB_SYNC),
          logging: ['error'],
        }) as TypeOrmModuleOptions,
    }),
    LogModule,

    // =========================================== 业务模块 ===========================================
    UserModule,
    AuthModule,
    RoleModule,
    HeroModule,
    UploadModule,
  ],
  controllers: [],
  providers: [
    Logger,
    {
      provide: APP_INTERCEPTOR,
      useClass: ApiResponseInterceptor,
    },
    {
      provide: APP_FILTER,
      useClass: ApiExceptionFilter,
    },
  ],
  exports: [Logger],
})
export class AppModule {}
